<?php

if( !defined( '_VALID_MOS' ) && !defined( '_JEXEC' ) ) die( 'Direct Access to '.basename(__FILE__).' is not allowed.' );

require_once(CLASSPATH ."payment/ps_kreditor_language.php");


class ps_kreditor {

    var $classname = "ps_kreditor";
    var $payment_code = "KREDITOR";
    
    /**
    * Show all configuration parameters for this payment method
    * @returns boolean False when the Payment method has no configration
    */
    function show_configuration() {
    

        
      define("KREDITOR_VERIFIED_STATUS_TEXT",'Choose the order status to which the current order should be set to if the payment is successful. If download options are used, make sure to select the status that makes downloading possible.');
      
      define("KREDITOR_INVALID_STATUS_TEXT",'Choose the order status for payments that fails.');
      
      define("KREDITOR_TESTMODE_TEXT",'Choose "Yes" for test mode to put invoices in test mode at Klarna.');
	  
	  define("KREDITOR_URL_CHARGE_TEXT", 'Enter how much you want to take as invoice fee (in crowns/euros) for payments made by invoice.');
	  	  
	  define("KREDITOR_VAT_SHIPPING_COST_TEXT", "Enter VAT (in %) for the shipping cost for ALL of the Klarna's payment methods");
	  
	  define("KREDITOR_VAT_INVOICE_FEE_TEXT", "Enter VAT (in %) for the invoice fee");
	  
	  define("KREDITOR_COUNTRIE_TEXT", "Which countries customers are allowed to shop?<br />Use ctrl + click on the countries you want to choose.");
      
	  define("KLARNA_INVOICE_FEE_TEXT", "What invoice fee should be charged for customers from \"this\" country?");
	  
      global $VM_LANG;
      $database = new ps_DB();
        /** Read current Configuration ***/
      require_once(CLASSPATH ."payment/".$this->classname.".cfg.php");
      $img_src_catalog_fixed_path = "../".KREDITOR_IMG_SRC_PATH;
    ?>
    <table class="adminform">
    <tr class="row1">
            <td><strong>Path to your picture</strong></td>
            <td>
                <input type="text" name="KREDITOR_IMG_SRC_PATH" class="inputbox" size="70" value="<?php echo KREDITOR_IMG_SRC_PATH ?>" />
            </td>
            <td>Specify the filename including the path.
            </td>
        </tr>
        <tr class="row0">
            <td><strong>Picture for payment method</strong></td>
            <td>
                <img src="<?php echo $img_src_catalog_fixed_path?>" >
            </td>
            <td>The picture (if any) will be looked up from joomla's root folder.
            </td>
        </tr>
		<tr class="row1">
			<td>
				<strong>EID</strong>
			</td>
            <td>
                <input type="text" name="KREDITOR_EID" class="inputbox" value="<?php  echo KREDITOR_EID ?>" />
            </td>
            <td>
				eID-number from Klarna.
			</td>
        </tr>
	
		<tr  class="row0">
			<td>
				<strong>Secret</strong>
			</td>
            <td>
                <input type="text" name="KREDITOR_SECRET" class="inputbox" value="<?php  echo KREDITOR_SECRET ?>" />
            </td>
            <td>
				The secret from Klarna.
			</td>
        </tr>	
         <tr class="row1">
            <td><strong><?php echo $VM_LANG->_('PHPSHOP_ADMIN_CFG_PAYPAL_STATUS_SUCCESS') ?>
			</strong></td>
            <td>
                <select name="KREDITOR_VERIFIED_STATUS" class="inputbox" >
                <?php
                    $q = "SELECT order_status_name,order_status_code FROM #__{vm}_order_status ORDER BY list_order";
                    $database->query($q);
                    $rows = $database->record;
                    $order_status_code = Array();
                    $order_status_name = Array();
                    
                    foreach( $rows as $row ) {
                      $order_status_code[] = $row->order_status_code;
                      $order_status_name[] =  $row->order_status_name;
                    }
                    for ($i = 0; $i < sizeof($order_status_code); $i++) {
                      echo "<option value=\"" . $order_status_code[$i];
                      if (KREDITOR_VERIFIED_STATUS == $order_status_code[$i]) 
                         echo "\" selected=\"selected\">";
                      else
                         echo "\">";
                      echo $order_status_name[$i] . "</option>\n";
                    }?>
                    </select>
            </td>
            <td><?php echo KREDITOR_VERIFIED_STATUS_TEXT ?>
            </td>
        </tr>
        <tr class="row0">
            <td><strong><?php echo $VM_LANG->_('PHPSHOP_ADMIN_CFG_PAYPAL_STATUS_FAILED') ?></strong></td>
            <td>
                <select name="KREDITOR_INVALID_STATUS" class="inputbox" >
                <?php
                    for ($i = 0; $i < sizeof($order_status_code); $i++) {
                      echo "<option value=\"" . $order_status_code[$i];
                      if (KREDITOR_INVALID_STATUS == $order_status_code[$i]) 
                         echo "\" selected=\"selected\">";
                      else
                         echo "\">";
                      echo $order_status_name[$i] . "</option>\n";
                    } ?>
                    </select>
            </td>
            <td><?php echo KREDITOR_INVALID_STATUS_TEXT ?>
            </td>
        </tr>
        <tr class="row1">
            <td><strong>Test Mode</strong></td>
            <td>
                <select name="KREDITOR_TESTMODE" class="inputbox" >
                  <option <?php if (KREDITOR_TESTMODE == 'Y') echo "selected=\"selected\""; ?> value="Y"><?php echo $VM_LANG->_('PHPSHOP_ADMIN_CFG_YES') ?></option>
                  <option <?php if (KREDITOR_TESTMODE == 'N') echo "selected=\"selected\""; ?> value="N"><?php echo $VM_LANG->_('PHPSHOP_ADMIN_CFG_NO') ?></option>
                </select>
            </td>
            <td><?php echo KREDITOR_TESTMODE_TEXT ?>
            </td>
        </tr><!--
        <tr class="row0">
            <td><strong>Enter the amount for the invoice fee</strong></td>
            <td>
				<input type="text" name="KREDITOR_URL_CHARGE" class="inputbox" value="<?php  //echo KREDITOR_URL_CHARGE ?>" />
            </td>
            <td><?php //echo KREDITOR_URL_CHARGE_TEXT ?>
            </td>
        </tr>
        --><!--
        <tr class="row1">
            <td><strong>Enter VAT (in %) for invoice fee</strong></td>
            <td>
			<input type="text" name="KREDITOR_VAT_INVOICE_FEE" class="inputbox" value="<?php //echo KREDITOR_VAT_INVOICE_FEE ?>" />
            </td>
            <td><?php //echo KREDITOR_VAT_INVOICE_FEE_TEXT ?>
            </td>
        </tr>
        -->
        <tr class="row0">
            <td><strong>Countries</strong></td>
            <td>
            	<select class="inputbox" name="KREDITOR_COUNTRIES[]" size="5" multiple="multiple">
            		<option value="SWEDEN" <?php if (KREDITOR_COUNTRIE_SWEDEN == 'Y') echo "selected=\"selected\""; ?>>Sweden</option>
            		<option value="NORWAY" <?php if (KREDITOR_COUNTRIE_NORWAY == 'Y') echo "selected=\"selected\""; ?>>Norway</option>
            		<option value="FINLAND" <?php if (KREDITOR_COUNTRIE_FINLAND == 'Y') echo "selected=\"selected\""; ?>>Finland</option>
            		<option value="DENMARK" <?php if (KREDITOR_COUNTRIE_DENMARK == 'Y') echo "selected=\"selected\""; ?>>Denmark</option>
            		<option value="GERMANY" <?php if (KREDITOR_COUNTRIE_GERMANY == 'Y') echo "selected=\"selected\""; ?>>Germany</option>
            		<option value="NETHERLAND" <?php if (KREDITOR_COUNTRIE_NETHERLAND == 'Y') echo "selected=\"selected\""; ?>>Netherland</option>
				</select>
            </td>
            <td><?php echo KREDITOR_COUNTRIE_TEXT ?></td>
        </tr>
        <tr class="row1">
            <td><strong>Invoice cost in <u>Sweden</u></strong></td>
            <td>
            	<input type="text" style="text-align: right" name="KLARNA_INVOICE_FEE_SWE" class="inputbox" value="<?php  echo KLARNA_INVOICE_FEE_SWE ?>" /> SEK <b>Including tax</b>
            </td>
            <td><?php echo KLARNA_INVOICE_FEE_TEXT ?></td>
        </tr>
        <tr class="row0">
            <td><strong>Invoice cost in <u>Norway</u></strong></td>
            <td>
            	<input type="text" style="text-align: right" name="KLARNA_INVOICE_FEE_NOR" class="inputbox" value="<?php  echo KLARNA_INVOICE_FEE_NOR ?>" /> NOK <b>Including tax</b>
            </td>
            <td><?php echo KLARNA_INVOICE_FEE_TEXT ?></td>
        </tr>
        <tr class="row1">
            <td><strong>Invoice cost in <u>Denmark</u></strong></td>
            <td>
            	<input type="text" style="text-align: right" name="KLARNA_INVOICE_FEE_DNK" class="inputbox" value="<?php  echo KLARNA_INVOICE_FEE_DNK ?>" /> DKK <b>Including tax</b>
            </td>
            <td><?php echo KLARNA_INVOICE_FEE_TEXT ?></td>
        </tr>
        <tr class="row0">
            <td><strong>Invoice cost in <u>Germany</u></strong></td>
            <td>
            	<input type="text" style="text-align: right" name="KLARNA_INVOICE_FEE_DEU" class="inputbox" value="<?php  echo KLARNA_INVOICE_FEE_DEU ?>" /> EUR <b>Including tax</b>
            </td>
            <td><?php echo KLARNA_INVOICE_FEE_TEXT ?></td>
        </tr>
        <tr class="row1">
            <td><strong>Invoice cost in <u>Finland</u></strong></td>
            <td>
            	<input type="text" style="text-align: right" name="KLARNA_INVOICE_FEE_FIN" class="inputbox" value="<?php  echo KLARNA_INVOICE_FEE_FIN ?>" /> EUR <b>Including tax</b>
            </td>
            <td><?php echo KLARNA_INVOICE_FEE_TEXT ?></td>
        </tr>
        <tr class="row1">
            <td><strong>Invoice cost in <u>Netherlands</u></strong></td>
            <td>
            	<input type="text" style="text-align: right" name="KLARNA_INVOICE_FEE_NLD" class="inputbox" value="<?php  echo KLARNA_INVOICE_FEE_NLD ?>" /> EUR <b>Including tax</b>
            </td>
            <td><?php echo KLARNA_INVOICE_FEE_TEXT ?></td>
        </tr>
<!--		<tr>-->
<!--			<td>Enter the yearly salary limit</td>-->
<!--			<td><input type="text" name="KREDITOR_YEARLY_SAL_LIMIT" class="inputbox" value="<?php //echo KREDITOR_YEARLY_SAL_LIMIT ?>" /></td>-->
<!--		</tr>-->
<!--		<tr>-->
<!--			<td>Enter the yearly salary limit</td>-->
<!--			<td><input type="text" name="KREDITOR_YEARLY_SAL_LIMIT" class="inputbox" value="<?php //echo KREDITOR_YEARLY_SAL_LIMIT ?>" /></td>-->
<!--		</tr>-->
<!--		<tr>-->
<!--			<td>Enter the yearly salary limit</td>-->
<!--			<td><input type="text" name="KREDITOR_YEARLY_SAL_LIMIT" class="inputbox" value="<?php //echo KREDITOR_YEARLY_SAL_LIMIT ?>" /></td>-->
<!--		</tr>-->
<!--		<tr>-->
<!--			<td>Enter the yearly salary limit</td>-->
<!--			<td><input type="text" name="KREDITOR_YEARLY_SAL_LIMIT" class="inputbox" value="<?php //echo KREDITOR_YEARLY_SAL_LIMIT ?>" /></td>-->
<!--		</tr>-->
<!--		<tr>-->
<!--			<td>Enter the yearly salary limit</td>-->
<!--			<td><input type="text" name="KREDITOR_YEARLY_SAL_LIMIT" class="inputbox" value="<?php //echo KREDITOR_YEARLY_SAL_LIMIT ?>" /></td>-->
<!--		</tr>-->
	</table>
    <?php
    }
    
    function has_configuration() {
      // return false if there's no configuration
      return true;
   }
   
  /**
	* Returns the "is_writeable" status of the configuration file
	* @param void
	* @returns boolean True when the configuration file is writeable, false when not
	*/
   function configfile_writeable() {
      return is_writeable( CLASSPATH."payment/".$this->classname.".cfg.php" );
   }
   
  /**
	* Returns the "is_readable" status of the configuration file
	* @param void
	* @returns boolean True when the configuration file is writeable, false when not
	*/
   function configfile_readable() {
      return is_readable( CLASSPATH."payment/".$this->classname.".cfg.php" );
   }

/**
	* Create table paytrans if not exist
	* @param -
	* @returns boolean True when writing was successful
	*/
     
   function db_paytrans(){
     $query = "CREATE TABLE IF NOT EXISTS `#__{vm}_paytrans` (
  `paytrans_id` int(11) unsigned NOT NULL auto_increment,
  `payment_processor` varchar(40) NOT NULL default '',
  `cart_id_number` varchar(40) NOT NULL default '',
  `customers_id` varchar(40) NOT NULL,
  `trans_order_id` varchar(40) default NULL,
  `orders_id` int(11) default NULL,
  `amount` decimal(15,4) default NULL,
  `currency` char(3) default NULL,
  `result` char(8) default NULL,
  `result_code` tinytext,
  `bank_code` tinytext,
  `trnumber` tinytext,
  `authcode` tinytext,
  `pay_result` tinytext,
  `pay_counter` int(11) default '0',
  `cc_descr` tinytext,
  `created` varchar(30) default NULL,
  `completed` varchar(30) default NULL,
  `temp_data` mediumtext,
  PRIMARY KEY  (`paytrans_id`)
) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=latin1";
	 $dbst = new ps_DB;
	 $dbst->setQuery($query);
	 $dbst->query();
	return true; 	
   }
  

/**
	* Alter table orders so that order_id is long enough for VirtueMart 1.1
	* @param -
	* @returns boolean True when writing was successful
	*/
     
   function db_orders(){
	 $query = "ALTER TABLE `#__{vm}_orders` MODIFY `order_number` varchar(40) NULL";
	 
	 
	 $dbst = new ps_DB;
	 $dbst->setQuery($query);
	 $dbst->query();
	return true; 
   }
  
  /**
	* Add a column for filename of picture if not exsist
	* @param -
	* @returns boolean True when writing was successful
	*/
     
   function db_paymentmethod(){
     
     $exists = false;
     $query = "show columns from #__{vm}_payment_method";
     
     $dbst = new ps_DB;
	 $dbst->setQuery($query);
	 $dbst->query();
	 
     while ($dbst->next_record() && !$exists) {
     	if ($dbst->f("Field") == 'payment_method_img_src') {
            $exists = true;
        }
     }      
     if(!$exists){
        $query="ALTER TABLE `#__{vm}_payment_method` ADD (`payment_method_img_src` varchar(64) default NULL)  ";
        $dbst->setQuery($query);
	    $dbst->query();
     }	 
	 
    }
    
    
    /**
	* Add a column for remainder_amount in ...._orders if not exsist
	* @param -
	* @returns boolean True when writing was successful
	*/
     
   function db_ordersAmountReminder(){
     
     $exists = false;
     $query = "show columns from #__{vm}_orders";
     
     $dbst = new ps_DB;
	 $dbst->setQuery($query);
	 $dbst->query();
	 
     while ($dbst->next_record() && !$exists) {
     	if ($dbst->f("Field") == 'remainder_amount') {
            $exists = true;
        }
     }      
     if(!$exists){
        $query="ALTER TABLE `#__{vm}_orders` ADD (`remainder_amount` decimal(15,5) default '0.00000')  ";
        $dbst->setQuery($query);
	    $dbst->query();
     }	  
    }

   /**
	* Add a column for faktura_pnr in ...._order_user_info if not exsist
	* @param -
	* @returns boolean True when writing was successful
	*/
   function db_orderuserinfoPnr(){
	 $exists = false;
     $query = "show columns from #__{vm}_order_user_info";
     
     $dbst = new ps_DB;
	 $dbst->setQuery($query);
	 $dbst->query();
	 
	 /*
     while ($dbst->next_record() && !$exists) {
     	if ($dbst->f("Field") == 'faktura_person_nr') {
            $exists = true;
        }
     }      
     if(!$exists){          
        $query="ALTER TABLE `#__{vm}_order_user_info` ADD (`faktura_person_nr` varchar(16) default NULL)  ";
        $dbst->setQuery($query);
	    $dbst->query();
     }	  */
	 
     while ($dbst->next_record() && !$exists) 
	 {
		switch($dbst->f("Field"))
		{
			case 'faktura_person_nr':
				$exists_pnr = true;
			break;
			
			case 'faktura_telefonnr':
				$exists_tfn = true;
			break;
			
			case 'faktura_mobilnr':
				$exists_mobilnr = true;
			break;
			
			case 'faktura_epost':
				$exists_epost = true;
			break;
		}
	}
           
     if(!$exists_pnr){
        $query="ALTER TABLE `#__{vm}_order_user_info` ADD (`faktura_person_nr` varchar(12) default NULL )   ";
        $dbst->setQuery($query);
	    $dbst->query();
     }	

	if(!$exists_tfn){
        $query="ALTER TABLE `#__{vm}_order_user_info` ADD (`faktura_telefonnr` varchar(15) default NULL )   ";
        $dbst->setQuery($query);
	    $dbst->query();
     }	

	if(!$exists_mobilnr){
        $query="ALTER TABLE `#__{vm}_order_user_info` ADD (`faktura_mobilnr` varchar(15) default NULL )   ";
        $dbst->setQuery($query);
	    $dbst->query();
     }	

	if(!$exists_epost){
        $query="ALTER TABLE `#__{vm}_order_user_info` ADD (`faktura_epost` varchar(40) default NULL )   ";
        $dbst->setQuery($query);
	    $dbst->query();
     }		
		 
   }
   
  /**
	* Writes filename of picture to table payment_method for this particular row
	* @param -
	* @returns boolean True when writing was successful
	*/
  
   function db_paymentmethod_setimgsrc( $img_src_path ){
	 $query = "UPDATE #__{vm}_payment_method SET payment_method_img_src='".$img_src_path."' WHERE payment_class='".$this->classname."'";
     
     $dbst = new ps_DB;
	 $dbst->setQuery($query);
	 $dbst->query();
   }
    
   function db_userfield(){ 
   	
   	 $query= "SELECT * FROM #__{vm}_userfield WHERE name='delimiter_faktura' ";
   	 $dbst = new ps_DB;
	 $dbst->setQuery($query);
	 $dbst->query();
	 if ($dbst->num_rows() == 0){
		$query = "
		into `#__{vm}_userfield` (`name`,`title`,`description`,`type`,`maxlength`,`size`,`required`,`ordering`,`cols`,`rows`,`value`,`default`,`published`,`faktura`,`shipping`,`account`,`readonly`,`calculated`,`sys`,`vendor_id`,`params`) values ('delimiter_faktura','PHPSHOP_ACCOUNT_FAKTURA_TITLE','','delimiter',25,30,0,36,NULL,NULL,NULL,NULL,1,0,0,1,0,0,0,1,NULL)";
		$dbst->setQuery($query);
	    $dbst->query();
	 }
   	
     $query= "SELECT * FROM #__{vm}_userfield WHERE name='faktura_person_nr' ";
     
	 $dbst->setQuery($query);
	 $dbst->query();
	 if ($dbst->num_rows() == 0){
		$query="insert into `#__{vm}_userfield` (`name`,`title`,`description`,`type`,`maxlength`,`size`,`required`,`ordering`,`cols`,`rows`,`value`,`default`,`published`,`faktura`,`shipping`,`account`,`readonly`,`calculated`,`sys`,`vendor_id`,`params`) values ('faktura_person_nr','PHPSHOP_ACCOUNT_LBL_FAKTURA_PERSON_NR','','text',12,12,0,37,NULL,NULL,NULL,NULL,1,0,0,1,0,0,1,1,NULL)";
		$dbst->setQuery($query);
	    $dbst->query();
	 }
	 
     $query= "SELECT * FROM #__{vm}_userfield WHERE name='faktura_telefonnr' ";
     
	 $dbst->setQuery($query);
	 $dbst->query();
	 if ($dbst->num_rows() == 0){
		$query="insert into `#__{vm}_userfield` (`name`,`title`,`description`,`type`,`maxlength`,`size`,`required`,`ordering`,`cols`,`rows`,`value`,`default`,`published`,`faktura`,`shipping`,`account`,`readonly`,`calculated`,`sys`,`vendor_id`,`params`) values ('faktura_telefonnr','PHPSHOP_ACCOUNT_LBL_FAKTURA_TELEFON_NR','','text',15,15,0,38,NULL,NULL,NULL,NULL,1,0,0,1,0,0,1,1,NULL)";
		$dbst->setQuery($query);
	    $dbst->query();
	 }	 
	 
     $query= "SELECT * FROM #__{vm}_userfield WHERE name='faktura_mobilnr' ";
     
	 $dbst->setQuery($query);
	 $dbst->query();
	 if ($dbst->num_rows() == 0){
		$query="insert into `#__{vm}_userfield` (`name`,`title`,`description`,`type`,`maxlength`,`size`,`required`,`ordering`,`cols`,`rows`,`value`,`default`,`published`,`faktura`,`shipping`,`account`,`readonly`,`calculated`,`sys`,`vendor_id`,`params`) values ('faktura_mobilnr','PHPSHOP_ACCOUNT_LBL_FAKTURA_MOBIL_NR','','text',15,15,0,39,NULL,NULL,NULL,NULL,1,0,0,1,0,0,1,1,NULL)";
		$dbst->setQuery($query);
	    $dbst->query();
	 }	 
	 
     $query= "SELECT * FROM #__{vm}_userfield WHERE name='faktura_epost' ";
     
	 $dbst->setQuery($query);
	 $dbst->query();
	 if ($dbst->num_rows() == 0){
		$query="insert into `#__{vm}_userfield` (`name`,`title`,`description`,`type`,`maxlength`,`size`,`required`,`ordering`,`cols`,`rows`,`value`,`default`,`published`,`faktura`,`shipping`,`account`,`readonly`,`calculated`,`sys`,`vendor_id`,`params`) values ('faktura_epost','PHPSHOP_ACCOUNT_LBL_FAKTURA_EPOST','','text',40,20,0,40,NULL,NULL,NULL,NULL,1,0,0,1,0,0,1,1,NULL)";
		$dbst->setQuery($query);
	    $dbst->query();
	 }	 	 
	 
   }// end function db_userfield
   
   function db_user_info(){
     
	 $exists = false;
     $query = "show columns from #__{vm}_user_info";
     
     $dbst = new ps_DB;
	 $dbst->setQuery($query);
	 $dbst->query();
	 
     while ($dbst->next_record() && !$exists) 
	 {
		switch($dbst->f("Field"))
		{
			case 'faktura_person_nr':
				$exists_pnr = true;
			break;
			
			case 'faktura_telefonnr':
				$exists_tfn = true;
			break;
			
			case 'faktura_mobilnr':
				$exists_mobilnr = true;
			break;
			
			case 'faktura_epost':
				$exists_epost = true;
			break;
		}
	}
           
     if(!$exists_pnr){
        $query="ALTER TABLE `#__{vm}_user_info` ADD (`faktura_person_nr` varchar(12) default NULL )   ";
        $dbst->setQuery($query);
	    $dbst->query();
     }	

	if(!$exists_tfn){
        $query="ALTER TABLE `#__{vm}_user_info` ADD (`faktura_telefonnr` varchar(15) default NULL )   ";
        $dbst->setQuery($query);
	    $dbst->query();
     }	

	if(!$exists_mobilnr){
        $query="ALTER TABLE `#__{vm}_user_info` ADD (`faktura_mobilnr` varchar(15) default NULL )   ";
        $dbst->setQuery($query);
	    $dbst->query();
     }	

	if(!$exists_epost){
        $query="ALTER TABLE `#__{vm}_user_info` ADD (`faktura_epost` varchar(40) default NULL )   ";
        $dbst->setQuery($query);
	    $dbst->query();
     }		 
	
   } // end function db_userinfo
   
    
   function db_invoices(){
	   $query = "CREATE TABLE IF NOT EXISTS `#__{vm}_invoices` (
         `invoices_id` int(11) unsigned NOT NULL auto_increment,
         `payment_processor` varchar(40) default 'EFFAKTURA',
         `customers_id` varchar(40) default NULL,
         `file_name` varchar(64) default NULL,
         `state` int(11) default '1',
         `amount` decimal(15,4) default NULL,
         `currency` char(3) default 'SEK',
         `created` varchar(30) default NULL,
         `completed` varchar(30) default NULL,
         PRIMARY KEY  (`invoices_id`)
         ) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=latin1";
	 $dbst = new ps_DB;
	 $dbst->setQuery($query);
	 $dbst->query();
	return true; 
   } //end function db_invoices
    
  /**
	* Writes the configuration file for this payment method
	* @param array An array of objects
	* @returns boolean True when writing was successful
	*/
   function write_configuration( &$d ) {
   	
   	  //first some databases stuff
   	  $this->db_paytrans();
   	  $this->db_orders();
   	  $this->db_paymentmethod();
   	  $this->db_ordersAmountReminder();
   	  $this->db_orderuserinfoPnr();
   	  $this->db_userfield();
   	  $this->db_user_info();
   	
   	  
   	  $this->db_invoices();
   	  //then data to db
   	  $this->db_paymentmethod_setimgsrc( $d['KREDITOR_IMG_SRC_PATH'] );
   	  //OK, ready
	  
		if (KREDITOR_TESTMODE == 'Y')
			$flags = $KRED_TEST_MODE;
		else 
			$flags = 0;

      $my_config_array = array(
                              "KREDITOR_EID" => $d['KREDITOR_EID'],
							  "KREDITOR_SHIPMENTFEE" => $d['KREDITOR_SHIPMENTFEE'],
							  "KREDITOR_HANDELINGFEE" => $d['KREDITOR_HANDELINGFEE'],
							  "KREDITOR_SECRET" => $d['KREDITOR_SECRET'],
							  "KREDITOR_VERIFIED_STATUS" => $d['KREDITOR_VERIFIED_STATUS'],
							  "KREDITOR_INVALID_STATUS" => $d['KREDITOR_INVALID_STATUS'],
							  "KREDITOR_TESTMODE" => $d['KREDITOR_TESTMODE'],
			                  "KREDITOR_IMG_SRC_PATH" => $d['KREDITOR_IMG_SRC_PATH'],
							  //"KREDITOR_URL_CHARGE" => str_replace(',','.',$d['KREDITOR_URL_CHARGE']),
      
						      "KLARNA_INVOICE_FEE_SWE" => str_replace(',','.',$d['KLARNA_INVOICE_FEE_SWE']),
						      "KLARNA_INVOICE_FEE_NOR" => str_replace(',','.',$d['KLARNA_INVOICE_FEE_NOR']),
						      "KLARNA_INVOICE_FEE_DNK" => str_replace(',','.',$d['KLARNA_INVOICE_FEE_DNK']),
						      "KLARNA_INVOICE_FEE_DEU" => str_replace(',','.',$d['KLARNA_INVOICE_FEE_DEU']),
						      "KLARNA_INVOICE_FEE_FIN" => str_replace(',','.',$d['KLARNA_INVOICE_FEE_FIN']),
     						  "KLARNA_INVOICE_FEE_NLD" => str_replace(',','.',$d['KLARNA_INVOICE_FEE_NLD']),
      
							  //"KREDITOR_VAT_INVOICE_FEE" => str_replace(',','.',$d['KREDITOR_VAT_INVOICE_FEE']),
							  //"KREDITOR_YEARLY_SAL_LIMIT" => $d['KREDITOR_YEARLY_SAL_LIMIT']
                            );
      $config = "<?php\n";
      $config .= "if( !defined( '_VALID_MOS' ) && !defined( '_JEXEC' ) ) die( 'Direct Access to '.basename(__FILE__).' is not allowed.' ); \n\n";
      foreach( $my_config_array as $key => $value ) {
        $config .= "define('$key', '$value');\n";
      }
      
      $config .= "?>";
		
		$my_LanguageConfig_array = array(
				"KREDITOR_COUNTRIE_SWEDEN" 		=> 'N',
				"KREDITOR_COUNTRIE_NORWAY" 		=> 'N',
				"KREDITOR_COUNTRIE_FINLAND" 	=> 'N',
				"KREDITOR_COUNTRIE_DENMARK" 	=> 'N',
				"KREDITOR_COUNTRIE_GERMANY" 	=> 'N',
				"KREDITOR_COUNTRIE_NETHERLAND" 	=> 'N',
										);
		
		if(!empty($d['KREDITOR_COUNTRIES'])) {
	   		foreach($d['KREDITOR_COUNTRIES'] as $key) {
	   			$my_LanguageConfig_array['KREDITOR_COUNTRIE_'.$key] = 'Y';
			}
		}
		
		$LanguageConfig = "<?php\n";
		$LanguageConfig .= "if( !defined( '_VALID_MOS' ) && !defined( '_JEXEC' ) ) die( 'Direct Access to '.basename(__FILE__).' is not allowed.' ); \n\n";
		foreach( $my_LanguageConfig_array as $key => $value ) 
		{
			$LanguageConfig .= "define('$key', '$value');\n";
		}

		$LanguageConfig .= "?>";


		if ($fp2 = fopen(CLASSPATH ."payment/ps_kreditor.common.cfg.php", "w")) 
		{
			fputs($fp2, $LanguageConfig, strlen($LanguageConfig));
			fclose ($fp2);
		}
  
		if ($fp = fopen(CLASSPATH ."payment/".$this->classname.".cfg.php", "w")) 
		{
			fputs($fp, $config, strlen($config));
			fclose ($fp);
			return true;
		}
		else
			return false;
   }
   
   /**
	* Validate ship to adress mot folkbokföringsadr
	* @param string personnummer, string shipinfoid
	* @returns int (-1 in case of error with personnummer, 0 if ok and unchanged, 1 if changed adress)
	*/
   function kreditor_shipto_validate($pno, $ship_to_info_id,&$d){
	//get databas content
    $db = new ps_DB;
    
    // Get ship to address
	$q = "SELECT last_name, first_name, address_1,city,country,zip FROM #__{vm}_user_info WHERE user_info_id ='".$ship_to_info_id."'";
	$db->query( $q );
	$db->next_record();
		

    $last_name = $db->f('last_name');
	$first_name= $db->f('first_name');
	$address_1 = $db->f('address_1');
	$city      = $db->f('city');
	$country_code   = $db->f('country'); 
	$zip       = $db->f('zip');
    
    require_once(CLASSPATH ."kreditor.php");
    
    switch ($country_code): 

	case 'SWE':
	 //Sweden
	 $country = "SWE";
	 $pnoencoding = $GLOBALS['$PNO_SE'];
	break;

	case 'DNK':
	  //Denmark
	  $country = "DNK";
	  $pnoencoding = $GLOBALS['$PNO_DK'];
	break;

	case 'NOR':
	  //Norway
	  $country = "NOR";
	  $pnoencoding = $GLOBALS['$PNO_NO'];
	break;
	// xxx Check finland
    case 'FIN':
	  //Finland
	  $country = "FIN";
	  $pnoencoding = $GLOBALS['$PNO_FI'];
	break;
	case 'DEU':
	  //Germany
	  $country = "DEU";
	  $pnoencoding = $GLOBALS['$PNO_DE'];
	break;
	case 'NLD':
	  //Netherland
	  $country = "NLD";
	  $pnoencoding = $GLOBALS['$PNO_NL'];
	break;
    endswitch;				
    
     
     require_once(CLASSPATH ."payment/ps_kreditor.cfg.php");
	 
     $type = $GLOBALS['$GA_OLD'];
	 
	 if($pnoencoding == $GLOBALS['$PNO_FI'] || $pnoencoding == $GLOBALS['$PNO_NO'] || $pnoencoding == $GLOBALS['$PNO_DE'] || $pnoencoding == $GLOBALS['$PNO_DK'] || $pnoencoding == $GLOBALS['$PNO_NL'])
		$status = 0;
	else
 		$status = get_addresses(KREDITOR_EID, $pno, KREDITOR_SECRET, $pnoencoding, $type, &$result);
	 
	 $test=0;
	 if ($test == 1){
                    switch ($status) {
                      case 0:
                       echo "<p>Addresses for customer: " . $pno . "<br/>";
                       foreach($result as $addr){
                         foreach($addr as $line){
                           echo $line . "<br/>\n";
                         }
                         echo "<br/>\n";
                       }
                    }
        echo "<br/>\n";
	    echo "Status= ". $status;   
	   print_r($status);  echo "<br/>\n";
	   print_r($result);
	   exit;
	 } 
	 
	if ($status == 0){
		
		if($pnoencoding == $GLOBALS['$PNO_FI']) {
			$k_fname = $first_name;
			$k_lname = $last_name;
			$k_street = $address_1;
			$k_postno = $zip;
			$k_city = $city;
			$k_country_code = 73;	//FIN
		} elseif($pnoencoding == $GLOBALS['$PNO_NO']) {
			$k_fname = $first_name;
			$k_lname = $last_name;
			$k_street = $address_1;
			$k_postno = $zip;
			$k_city = $city;
			$k_country_code = 164;	//NO
		} elseif($pnoencoding == $GLOBALS['$PNO_DE']) {
			$k_fname = $first_name;
			$k_lname = $last_name;
			$k_street = $address_1;
			$k_postno = $zip;
			$k_city =  $city;
			$k_country_code = 81;	//DE
		} elseif($pnoencoding == $GLOBALS['$PNO_DK']) {
			$k_fname = $first_name;
			$k_lname = $last_name;
			$k_street = $address_1;
			$k_postno = $zip;
			$k_city =  $city;
			$k_country_code = 59;	//DK
		} elseif($pnoencoding == $GLOBALS['$PNO_NL']) {
			$k_fname = $first_name;
			$k_lname = $last_name;
			$k_street = $address_1;
			$k_postno = $zip;
			$k_city =  $city;
			$k_country_code = 154;	//NL
		} else {
			$k_fname = utf8_encode($result[0][0]);
			$k_lname = utf8_encode($result[0][1]);
			$k_street = utf8_encode($result[0][2]);
			$k_postno = utf8_encode($result[0][3]);
			$k_city = utf8_encode($result[0][4]);   	
			$k_country_code = $result[0][5];
		}
		
		switch ($k_country_code): 

		case 209:
			//Sweden
			$k_country = "SWE";
		break;

		case 59:
			//Denmark
			$k_country = "DNK";
		break;

		case 164:
			//Norway
			$k_country = "NOR";
		break;

	    case 73:
		  //Finland
		  $k_country = "FIN";
		break;

	    case 81:
			//Germany
			$k_country = "DEU";	    	
	    break;
		
	    case 154:
			//Netherland
			$k_country = "NLD";	    	
	    break;
	    
		default :
		$k_country = "SWE";

	    endswitch;				
		
	    // start compare
	    $equal = false;
		
		if(($country == $k_country) && 
			(strtolower($city) == strtolower($k_city)) && 
			(str_replace(' ','',$zip) == str_replace(' ','',$k_postno)) && 
			(strtolower($address_1) == strtolower($k_street)) && 
			(strtolower($address_1) == strtolower($k_street)) &&
			(strtolower($last_name) == strtolower($k_lname)) &&
			(strtolower($first_name) == strtolower($k_fname))) {
			
			$equal = true;
		}
	}
	
	if (($status == 0) AND ($equal == false)){

		 //update the kaschmack
		 // Get ship to address
	     $q = "UPDATE #__{vm}_user_info SET last_name ='". $k_lname ."',
		                                    first_name='". $k_fname ."',
										    address_1 ='". $k_street ."',
											city      ='". $k_city ."',
											country   ='". $k_country ."',
											zip       ='". $k_postno ."'  WHERE user_info_id ='".$ship_to_info_id."'";
	     $db->query( $q );
	     $d['last_name']  = $k_lname;
	     $d['first_name'] = $k_fname;
	     $d['address_1']  = $k_street;
	     $d['city']       = $k_city;
	     $d['country']    = $k_country;
	     $d['zip']        = $k_postno;
	     
		$result2 = 1;
	} else if (($status == 0) AND ($equal == true)){
		$result2 = 0;
	} else {
		$result2 = utf8_encode($result);
	}
     return $result2;
   }
   
  /**************************************************************************
  ** name: process_payment()
  ** returns: 
  ***************************************************************************/
   function process_payment($order_number, $order_total, &$d) 
   {
	
   	 //print_r($d); exit;
   	 // echo $_REQUEST['shipping_rate_id']; exit;
   	
      if ( !isset($d['order_status']) )
	  {
      	   // prevent second call tp ps_checkout::add() to pick another order_number
      	   $d['order_number'] = $order_number;
   	       $d_commasep = "";	
   	       foreach ($d as $key => $value) {
              //echo "Parameter: $key; Value: $value<br />\n";
              $d_commasep .= $key ."," . $value .";";
           }	
   	      $now=date("Y-m-d H:i:s");
   	      $q2  = "INSERT INTO #__{vm}_paytrans SET payment_processor='KREDITOR' " .
			     ", customers_id   = '".$d['ship_to_info_id']."'" .
				 ", trans_order_id = '".$order_number."'" .
				 ", amount         = '".$order_total."'" .
				 ", currency       = '".$_SESSION['vendor_currency']."'" .
				 ", created        = '".$now."'".
				 ", temp_data      = '".$d_commasep."'";
				  
	      $dbst = new ps_DB;
	      $dbst->setQuery($q2);
	      $dbst->query();
	      //----------------Make goods list and stuff to Kreditor-------------------------------
	      require_once(CLASSPATH ."payment/ps_kreditor.cfg.php");
	      require_once(CLASSPATH ."kreditor.php");
		  require_once(CLASSPATH ."ps_product.php");
		  require_once(CLASSPATH . 'klarna_util.php');
		  $ps_product = new ps_product();	
	      // Get shoppingcart
		  $cart = $_SESSION['cart'];
		
		  // goods
		  $goods = array();
		
		  //Used for calculating the invoice tax later on.
		  for ($i=0;$i<$cart["idx"];$i++) 
		  {
			// Quantity
			$qty = $cart[$i]["quantity"];
			
			// Product name
			$name = $ps_product->get_field($_SESSION['cart'][$i]["product_id"], "product_name");

			// Product model
			$model = $ps_product->get_field($cart[$i]["product_id"], "product_sku");

			// Product description
			$desc = $ps_product->getDescriptionWithTax( $_SESSION['cart'][$i]["description"], $_SESSION['cart'][$i]["product_id"] );
			$desc = str_replace( "<br/>", ";", $desc);
			$name = $name . ' ' . $desc;
			
			// Product tax
			$my_taxrate = $ps_product->get_product_taxrate($cart[$i]["product_id"]);
			$tax = $my_taxrate * 100;
			
			// Product price
			$prince_info = $ps_product->get_adjusted_attribute_price($cart[$i]["product_id"], $cart[$i]["description"]);
			$prince_info["product_price"] = $prince_info["product_price"] * ($my_taxrate+1);
			$final_price = round($GLOBALS['CURRENCY']->convert( $prince_info["product_price"], @$prince_info["product_currency"] ), 2)*100;
			$is_discount = $prince_info['discount_info'];
			
			
			//IF DISCOUNT
			if(isset($is_discount))
			{
				if(strstr($is_discount,"%"))
				{
					$discount_vat = explode(" ", $is_discount);
					$discount_vat[2] = substr_replace($discount_vat[2] ,"",-1);
					// Add product to goodslist
					$goods[] = mk_goods_flags(intval($qty), utf8_decode($model), utf8_decode($name), $final_price, $tax, $discount_vat[2], 32);
				}
				else
				{
					// Add product to goodslist
					$goods[] = mk_goods_flags(intval($qty), utf8_decode($model), utf8_decode($name), $final_price, $tax, 0, 32);	
				}
			}
			else
			{
				// Add product to goodslist
				$goods[] = mk_goods_flags(intval($qty), utf8_decode($model), utf8_decode($name), $final_price, $tax, 0, 32);			
			}
		}
	    
    	$db2 = new ps_DB;
		$q2 = "SELECT vendor_country FROM #__{vm}_vendor WHERE vendor_id = '" . $_SESSION['ps_vendor_id'] . "';";
		$db2->query($q2);
		$vendor_countrie = $db2->f("vendor_country");

		$klarna_vat_invoice_fee = getKlarnaInvoiceTax();
		
		activateLanguage();
		$langInfo = new Singleton("language");
		//$charges = round($GLOBALS['CURRENCY']->convert(KREDITOR_URL_CHARGE, @$prince_info["product_currency"] ), 2)*100;
		require_once(CLASSPATH . 'klarna_util.php');
		$goods[] = mk_goods_flags(1, 0, utf8_decode($langInfo->TEXT_INVOICE_COST), (getKlarnaInvoiceCost()*100), $klarna_vat_invoice_fee, 0, 48);
		
		// THE ORDER OF THOSE VALUES IS IMPORTANT:
		// ShippingClassName|carrier_name|rate_name|totalshippingcosts|rate_id
		$details = explode( "|", urldecode( $d['shipping_rate_id'] ) ) ;
		//print_r($details);

		if($vendor_countrie == 'SWE') {
			$goods[] = mk_goods_flags(1, 0, $details[1], round(($d['shipping_total'] + $d['shipping_tax']), 2)*100, $klarna_vat_invoice_fee, 0, 40);
		} else {
			require_once(CLASSPATH ."ps_checkout.php");
			$ps_checkout = new ps_checkout();		
			$goods[] = mk_goods_flags(1, 0, $details[1], round(($d['shipping_total'] + $d['shipping_tax']), 2)*100, $ps_checkout->_SHIPPING->get_tax_rate()*100, 0, 40);
		}
		//print_r($cart);
		//echo "<br /><br /><br />";
		//print_r($goods);
		//exit;
		
		//------------------------------ship, discount etc------------------------------
	    /*
	    $d['order_subtotal_withtax'] = 475.37;
		$d['payment_discount'] = -45;
		$d['order_tax'] = 36.23;
	    $d['shipping_tax'] = 0;
		$d['shipping_total'] = 7;
		$d['order_shipping'] = 7; 
		$d['order_shipping_tax'] = 0;
		$d['order_total'] = 527.370877598;	
		*/
	    if (!empty($_SESSION['coupon_discount']) ){
			$qty = 1;
			$model ="";
			$name = $langInfo->TEXT_DISCOUNT;
			$product_price = round($GLOBALS['CURRENCY']->convert((-1* $_SESSION['coupon_discount']), @$prince_info["product_currency"] ), 2) * 100;
			// Add rabatter to goodslist
			$goods[] = mk_goods_flags(intval($qty), $model, $name, $product_price, $tax, 0, 32);
		}
		
		//--------- customer adr-----------------------------------------------------
		// Get ship to address
		$q = "SELECT last_name, first_name,user_email,phone_1,phone_2,address_1,city,country,zip,faktura_person_nr,faktura_telefonnr,faktura_mobilnr,faktura_epost FROM #__{vm}_user_info WHERE user_info_id ='". $d['ship_to_info_id'] ."'";
	    $dbst->query( $q );
	    $dbst->next_record();
	
	    $country_code   = $dbst->f('country');
	    
		$customer = array();
		
		$customer['pno']    = $_COOKIE["pnr"];//xxx$dbst->f('faktura_person_nr');
		// As we dont want to store the users "personnummer" for longer time than neccessary we delete the cookie when we have used it.
		setCookie("pnr", "", time()-3600);
		$customer['fname']  = $dbst->f('first_name');
		$customer['lname']  = $dbst->f('last_name');
		$customer['street'] = $dbst->f('address_1');
		$customer['postno'] = $dbst->f('zip');
		$customer['city']   = $dbst->f('city');
		$customer['telno'] = $dbst->f('faktura_telefonnr');
		$customer['cellno'] = $dbst->f('faktura_mobilnr');
		$customer['email'] = $dbst->f('faktura_epost');
		
		//print_r($customer); exit;
		 
		 // print_r($_SESSION['coupon_discount']); exit;
	      //--------------------------------------------------
	      $eid = KREDITOR_EID;
		  $estoreUser = "";
		  $secret = KREDITOR_SECRET;
		  $estoreOrderNo = "";
		  //$goods = $_SESSION['kreditor_goods'];
		  //$customer = $_SESSION['kreditor_customer'];	
		  //ex moms	  
		  $shipmentfee = 0; //($d['shipping_total'] + $d['shipping_tax']) * 100 * 0.8;
		  $shipmenttype = 1;
		  //ex moms
		  $handlingfee = 0;
		  $pno = $customer['pno'] . $_COOKIE["gender"];
		  setCookie("gender", "", time()-3600);
		  $fname = utf8_decode($customer['fname']);
		  $lname = utf8_decode($customer['lname']);
		  $street = utf8_decode($customer['street']);
		  $postno = $customer['postno'];
		  $city = utf8_decode($customer['city']);
		  $telno = $customer['telno'];
		  $cellno = $customer['cellno'];
		  $email = $customer['email'];
		  $comment = "";
		  $passwd = "";
		  $clientIp = $_SERVER["REMOTE_ADDR"];
		  $newPasswd = "";
		  $ip = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
		
		  if (KREDITOR_TESTMODE == 'Y')
		     $flags = $KRED_TEST_MODE;
		  else 
			 $flags = 0;
	
		  $ready_date = "";
		  $rand_string = "";
		  
		  
		switch($country_code)
		{
			case 'SWE':
				//Sweden
				$pnoencoding = $GLOBALS['$PNO_SE'];
				$addr = mk_addr_se("", $street, $postno, $city, $telno, $cellno, $email);
				$country = $GLOBALS['KRED_ISO3166_SE'];
				$language = $GLOBALS['KRED_ISO639_SV'];
				$currency = $GLOBALS['$KRED_SEK'];
				break;
			case 'DNK':
				//Denmark
				$pnoencoding = $GLOBALS['$PNO_DK'];
				$addr = mk_addr_dk("", $street, $postno, $city, $telno, $cellno, $email);
				$country = $GLOBALS['KRED_ISO3166_DK'];
				$language = $GLOBALS['KRED_ISO639_DA'];
				$currency = $GLOBALS['$KRED_DKK'];
				break;
			case 'NOR':
				//Norway
				$pnoencoding = $GLOBALS['$PNO_NO'];
				$addr = mk_addr_no("", $street, $postno, $city, $telno, $cellno, $email);
				$country = $GLOBALS['KRED_ISO3166_NO'];
				$language = $GLOBALS['KRED_ISO639_NB'];
				$currency = $GLOBALS['$KRED_NOK'];
				break;
			case 'FIN':
				//Finland
				$pnoencoding = $GLOBALS['$PNO_FI'];
				$addr = mk_addr_fi("", $street, $postno, $city, $telno, $cellno, $email);
				$country = $GLOBALS['KRED_ISO3166_FI'];
				$language = $GLOBALS['KRED_ISO639_FI'];
				$currency = $GLOBALS['$KRED_EUR'];
				break;
			case 'DEU':
				//Germany
				$pnoencoding = $GLOBALS['$PNO_DE'];
				$addr = mk_addr_de("", utf8_decode($_COOKIE["streetname"]), $postno, $city, $telno, $cellno, $email, $_COOKIE["streetnumber"]);
				$country = $GLOBALS['KRED_ISO3166_DE'];
				$language = $GLOBALS['KRED_ISO639_DE'];
				$currency = $GLOBALS['$KRED_EUR'];
				setCookie("streetname", "", time()-3600);
				setCookie("streetnumber", "", time()-3600);
				break;
			case 'NLD':
				//Netherlands
				$pnoencoding = $GLOBALS['$PNO_NL'];
				$addr = mk_addr_nl("", utf8_decode($_COOKIE["streetname"]), $postno, $city, $telno, $cellno, $email, $_COOKIE["streetnumber"], utf8_decode($_COOKIE["houseext"]));
				$country = $GLOBALS['KRED_ISO3166_NL'];
				$language = $GLOBALS['KRED_ISO639_NL'];
				$currency = $GLOBALS['$KRED_EUR'];
				setCookie("streetname", "", time()-3600);
				setCookie("streetnumber", "", time()-3600);
				setCookie("houseext", "", time()-3600);
				break;
			default:
				$pnoencoding = $GLOBALS['$PNO_SE'];
				$addr = mk_addr_se("", $street, $postno, $city, $telno, $cellno, $email);
				$country = $GLOBALS['KRED_ISO3166_SE'];
				$language = $GLOBALS['KRED_ISO639_SV'];
				$currency = $GLOBALS['$KRED_SEK'];
				break;
		}	
		  
		  // echo "eid: " . $eid . "<br />";
		  // echo "estoreUser: " . $estoreUser . "<br />";
		  // echo "secret: " . $secret . "<br />";
		  // echo "goods: " . $goods . "<br />";
		  // echo "shipmentfee: " . $shipmentfee . "<br />";
		  // echo "shipmenttype: " . $shipmenttype . "<br />";
		  // echo "handlingfee: " . $handlingfee . "<br />";
		  // echo "pno: " . $pno . "<br />";
		  // echo "fname: " . $fname . "<br />";
		  // echo "lname: " . $lname . "<br />";
		  // echo "addr: " . $addr . "<br />";
		  // echo "d['payment_discount']: " . $d['payment_discount'] . "<br />";
		  // echo "clientIp: " . $clientIp . "<br />";
		  // echo "newPasswd: " . $newPasswd . "<br />";
		  // echo "flags: " . $flags . "<br />";
		  // echo "comment: " . $comment . "<br />";
		  // echo "ready_date: " . $ready_date . "<br />";
		  // echo "rand_string: " . $rand_string . "<br />";
		  // echo "pclassInfo_currency: " . $pclassInfo_currency . "<br />";
		  // echo "country: " . $country . "<br />";
		  // echo "language: " . $language . "<br />";
		  // echo "pnoencoding: " . $pnoencoding . "<br />";
		  
		  // echo "d['shipping_tax']: " . $d['shipping_tax'] . "<br />";
		  // echo "d['shipping_total']: " . $d['shipping_total'] . "<br />";
		  // echo "d['order_shipping']: " . $d['order_shipping'] . "<br />";
		  // echo "d['order_shipping_tax']: " . $d['order_shipping_tax'] . "<br />";
		  
		  //exit;
		
		
//	  	$db = new ps_DB;
//		$q  = "SELECT * from #__{vm}_user_info WHERE user_id='" . $_SESSION['auth']['user_id'] . "' AND address_type='BT'";
//		$db->query($q);
//		
//		$living_in_country = $db->f('country');
		
		
		$langInfo = new Singleton("Currency");
		switch($country_code)
		{
			case "SWE": $langInfo->Currency_Customer_Credit = "SEK"; break;
			case "NOR": $langInfo->Currency_Customer_Credit = "NOK"; break;
			case "DNK": $langInfo->Currency_Customer_Credit = "DKK"; break;
			
			case "NLD":
			case "DEU":
			case "FIN": $langInfo->Currency_Customer_Credit = "EUR"; break;
		}
		
		$do_add_transaction = true;
		if(isset($_SESSION['product_currency'])) {
			if($langInfo->Currency_Customer_Credit != $_SESSION['product_currency']) {
				$do_add_transaction = false;
			}
		} else {
			if($langInfo->Currency_Customer_Credit != $_SESSION['vendor_currency']) {
				$do_add_transaction = false;
			}
		}
		
		$status = -13231;
		if($do_add_transaction) {
				$status = add_transaction($eid, $estoreUser, $secret, $estoreOrderNo,  $goods,
					 $shipmentfee, $shipmenttype, $handlingfee, $pno, $fname,
					 $lname, $addr, $passwd, $clientIp, $newPasswd, $flags,
					 $comment, $ready_date, $rand_string, $currency, $country, $language, $pnoencoding, -1, $_COOKIE["ysalary"]*100, $result);
		}
	      
          if ($status == 0){
			$payresult = "APPROVED";
		  } else {
		    $payresult = "DECLINED";
		  }
		  
	      $q2  = "UPDATE  #__{vm}_paytrans SET pay_result = '".$payresult."', trnumber='".$result."' WHERE trans_order_id = '".$order_number."'";		 
	      $dbst->setQuery($q2);
	      $dbst->query();
	      
	      $_GET['order_number'] = $order_number;
	      $_SESSION['faktura_number'] = utf8_encode($result);
	      if(!$do_add_transaction) {
		      $langInfo = new Singleton("language");
		      $_SESSION['currency_error'] = $langInfo->TEXT_PAYMENT_CURRENCY_ERROR;
	      }
	      
	      $url="index.php?Itemid=1&option=com_virtuemart&page=checkout.kreditor";

          foreach ($_GET as $key => $value) {
            //echo "Parameter: $key; Value: $value<br />\n";
            $url .= "&" . $key ."=" . $value;
          }

          $host  = $_SERVER['HTTP_HOST'];
          $uri   = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
          header("Location: http://". $host . $uri ."/". $url );
  
          exit();
 
	      //------------------------------------------------------------------------------------
		} else {
   	      require_once(CLASSPATH ."payment/".$this->classname.".cfg.php");
   	      // kolla betstatus
   	      //return true om ok annars return false
          if ($d['order_status'] == KREDITOR_VERIFIED_STATUS)  {
             return true;
            //order payed
          } else { 
			return false;
			//order not payed
		  } // end if betalt
		} // end if
     
   
   } //end function process_payment
   
}

?>